<template>
  <div class="menu-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>菜单管理</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加菜单
          </el-button>
        </div>
      </template>

      <!-- 菜单树表格 -->
      <el-table
        :data="menuList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="菜单名称" />
        <el-table-column prop="path" label="路径" />
        <el-table-column prop="component" label="组件" />
        <el-table-column label="图标">
          <template #default="{ row }">
            <el-icon v-if="row.icon">
              <component :is="row.icon" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="sort_order" label="排序" width="80" />
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="权限">
          <template #default="{ row }">
            <el-tag
              v-for="permission in row.permissions"
              :key="permission.id"
              type="info"
              size="small"
              style="margin-right: 5px;"
            >
              {{ permission.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="showEditDialog(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteMenu(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑菜单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="menuForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menuForm.name" />
        </el-form-item>
        <el-form-item label="菜单路径" prop="path">
          <el-input v-model="menuForm.path" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model="menuForm.component" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="menuForm.icon" />
        </el-form-item>
        <el-form-item label="父菜单" prop="parent">
          <el-select
            v-model="menuForm.parent"
            placeholder="请选择父菜单"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="menu in parentMenuOptions"
              :key="menu.id"
              :label="menu.name"
              :value="menu.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input-number v-model="menuForm.sort_order" :min="0" />
        </el-form-item>
        <el-form-item label="所需权限" prop="permission_ids">
          <el-select
            v-model="menuForm.permission_ids"
            multiple
            placeholder="请选择所需权限"
            style="width: 100%"
          >
            <el-option
              v-for="permission in permissionList"
              :key="permission.id"
              :label="permission.name"
              :value="permission.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="menuForm.is_active" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import api from '@/utils/api'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加菜单')
const isEdit = ref(false)
const editMenuId = ref(0)

const menuList = ref([])
const permissionList = ref([])
const formRef = ref<FormInstance>()

// 菜单表单
const menuForm = reactive({
  name: '',
  path: '',
  component: '',
  icon: '',
  parent: null,
  sort_order: 0,
  permission_ids: [],
  is_active: true
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入菜单路径', trigger: 'blur' }
  ]
}

// 父菜单选项（排除当前编辑的菜单及其子菜单）
const parentMenuOptions = computed(() => {
  const flattenMenus = (menus: any[], level = 0): any[] => {
    let result: any[] = []
    menus.forEach(menu => {
      if (isEdit.value && menu.id === editMenuId.value) {
        return // 排除当前编辑的菜单
      }
      result.push({
        ...menu,
        name: '　'.repeat(level) + menu.name
      })
      if (menu.children && menu.children.length > 0) {
        result = result.concat(flattenMenus(menu.children, level + 1))
      }
    })
    return result
  }
  
  return flattenMenus(menuList.value)
})

// 获取菜单列表
const fetchMenuList = async () => {
  loading.value = true
  try {
    const response = await api.get('/rbac/menus/')
    if (response.data.success) {
      menuList.value = response.data.data
    }
  } catch (error) {
    console.error('获取菜单列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取权限列表
const fetchPermissionList = async () => {
  try {
    const response = await api.get('/rbac/permissions/')
    if (response.data.success) {
      permissionList.value = response.data.data.results
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
  }
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加菜单'
  isEdit.value = false
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (menu: any) => {
  dialogTitle.value = '编辑菜单'
  isEdit.value = true
  editMenuId.value = menu.id
  
  Object.assign(menuForm, {
    name: menu.name,
    path: menu.path,
    component: menu.component || '',
    icon: menu.icon || '',
    parent: menu.parent?.id || null,
    sort_order: menu.sort_order,
    permission_ids: menu.permissions?.map((p: any) => p.id) || [],
    is_active: menu.is_active
  })
  
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(menuForm, {
    name: '',
    path: '',
    component: '',
    icon: '',
    parent: null,
    sort_order: 0,
    permission_ids: [],
    is_active: true
  })
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        let response
        if (isEdit.value) {
          response = await api.put(`/rbac/menus/${editMenuId.value}/`, menuForm)
        } else {
          response = await api.post('/rbac/menus/', menuForm)
        }
        
        if (response.data.success) {
          ElMessage.success(`菜单${isEdit.value ? '更新' : '创建'}成功`)
          dialogVisible.value = false
          fetchMenuList()
        }
      } catch (error) {
        console.error('操作失败:', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 删除菜单
const deleteMenu = async (menu: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单 ${menu.name} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await api.delete(`/rbac/menus/${menu.id}/`)
    if (response.data.success) {
      ElMessage.success('菜单删除成功')
      fetchMenuList()
    }
  } catch (error) {
    // 用户取消操作
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchMenuList()
  fetchPermissionList()
})
</script>

<style scoped>
.menu-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
